(function (window, angular) {
  "use strict";
  angular.module("Controller.Maintenance.fanchangHexiao", []).controller("FanchangHexiaoCtrl", [
    "$scope",
    "ybWidget",
    "ybHttp",
    "MESG_TYPE",
    "$timeout",
    "$filter",
    "UserContextService",
    function (
      $scope,
      ybWidget,
      ybHttp,
      MESG_TYPE,
      $timeout,
      $filter,
      UserContextService,
    ) {

      $scope.activeFlag = [true, false, false, false, false];
      $scope.markInfo = {
        allChecked: false,
      };
      $scope.pageInfo = {
        totalPages: 1,
        totalRows: 0,
        pageSize: 10,
        curPage: 1,
      };
      $scope.toolbarConfig = {
        showAdvanceSearch: false,
        showColConfig: false,
      };

      $scope.exportParam = {
        sectionUrl: ybHttp.RequestUrl("mt", "/hexiao/export"),
        sectionParam: {ids: []},
        allUrl: ybHttp.RequestUrl("mt", "/hexiao/exportAll")
      };

      $scope.dataList = [];
      $scope.condition = {};

      $scope.tbConf = {
        fixedWidth: 100,
        scrollWidth: 1700,
        tableCol: [
          {
            name: "核销单号",
            width: 140,
            dataField: "billNo",
            isShow: true,
            isFixed: false,
            clickFn: "viewDetail",
          },
          {
            name: "审核人",
            dataField: "auditUserName",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          {
            name: "审核状态",
            width: 100,
            dataField: "auditStatusShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "审核日期",
            dataField: "auditDateShow",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          {
            name: "发票号",
            width: 150,
            dataField: "fapiaoNo",
            isShow: true,
            isFixed: false,
          },
          {
            name: "发票金额",
            width: 120,
            dataField: "fapiaoPrice",
            isShow: true,
            isFixed: false,
          },
          {
            name: "申请人",
            width: 120,
            dataField: "applyUserName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "联系方式",
            width: 120,
            dataField: "telephone",
            isShow: true,
            isFixed: false,
          },
          {
            name: "服务单位",
            width: 160,
            dataField: "serviceOrgName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "申请时间",
            width: 140,
            dataField: "applyDateShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "发运方式",
            width: 100,
            dataField: "sendMethodName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "承运公司",
            width: 160,
            dataField: "carrierName",
            isShow: true,
            isFixed: false,
          },
          {
            name: "预计到达日期",
            width: 100,
            dataField: "etaShow",
            isShow: true,
            isFixed: false,
          },
          {
            name: "物流单号",
            width: 160,
            dataField: "logisticsNo",
            isShow: true,
            isFixed: false,
          },
          {
            name: "司机电话",
            width: 120,
            dataField: "driverPhone",
            isShow: true,
            isFixed: false,
          },
          {
            name: "提交时间",
            dataField: "createDateShow",
            width: 140,
            isShow: true,
            isFixed: false,
          },
          {
            name: "操作",
            isShow: true,
            isFixed: true,
          },
        ],
      };

      $scope.setFixedWidth = function () {
        $scope.tbStyle = {
          scrollLeft: {
            left: $scope.tbConf.fixedWidth + "px",
          },
        };
      };

      $scope.switchToolbar = function (toolbar) {
        if (!!$scope.toolbarConfig["show" + toolbar]) {
          $scope.toolbarConfig["show" + toolbar] = false;
        } else {
          $timeout(function () {
            $scope.toolbarConfig["show" + toolbar] = true;
          });
        }
      };

      $scope.changeTab = function (index) {
        $scope.activeFlag = [false, false];
        $scope.activeFlag[index] = true;
        $scope.submitted = false;
      };

      $scope.search = function (curpage) {
        getDataList(curpage);
      };

      $scope.reset = function () {
        $scope.condition = {};
      };

      function getDataList(curPage) {
        if (!!curPage) {
          $scope.pageInfo.curPage = curPage;
        }
        var param = {
          pageSize: $scope.pageInfo.pageSize,
          pageNum: $scope.pageInfo.curPage,
          filters: $scope.condition,
        };
        ybHttp.Post("mt", "/hexiao/list", param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          $scope.markInfo.allChecked = false;
          angular.forEach(resp.value.list, function (item) {
            item.isChecked = false;
            item.applyDateShow = $filter("YbDate")(item.applyDate, "yyyy-MM-dd HH:mm:ss");
            item.etaShow = $filter("YbDate")(item.eta, "yyyy-MM-dd");
            item.createDateShow = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
            item.auditStatusShow = $filter("AuditStatus2")(item.auditStatus);
            item.auditDateShow = $filter("YbDate")(item.auditDate, "yyyy-MM-dd HH:mm:ss");
          });
          $scope.pageInfo.totalRows = resp.value.total;
          $scope.pageInfo.totalPages = resp.value.pages;
          $scope.dataList = resp.value.list;
        });
      }

      $scope.selectRow = function (index) {
        $scope.markInfo.curRow = index;
      };

      function checkAll() {
        var selectAllFlag = false;
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          if (!$scope.dataList[i].isChecked) {
            selectAllFlag = false;
            break;
          }
          selectAllFlag = true;
        }
        return selectAllFlag;
      }

      $scope.selectSingle = function (item) {
        if (!item.isChecked) {
          $scope.markInfo.allChecked = false;
        } else {
          if (!checkAll()) {
            $scope.markInfo.allChecked = false;
          } else {
            $scope.markInfo.allChecked = true;
          }
        }
        getBillIds();
      };

      $scope.selectAll = function () {
        for (var i = 0, len = $scope.dataList.length; i < len; i++) {
          $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
        }
        getBillIds();
      };

      function getBillIds() {
        $scope.exportParam.sectionParam.ids = [];
        angular.forEach($scope.dataList, function (item) {
          if (!!item.isChecked) {
            $scope.exportParam.sectionParam.ids.push(item.id);
          }
        });
      }

      $scope.orderObj = {};
      $scope.viewDetail = function (val) {
        getDetail(val).then(function (value) {
          if (!value) {
            return;
          }

          $scope.orderObj = value;
          $scope.changeTab(1);
        });
      };

      function getDetail(val) {
        var reqUrl = "/hexiao/item";
        var param = { id: val };
        return ybHttp.Get("mt", reqUrl, param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return false;
          }
          const valT = resp.value
          if (valT && valT.details) {
            angular.forEach(valT.details, function (item) {
              item.hexiaoShow = $filter("TrueOrFalseOrNull")(item.hexiao);
              item.purchaseDateShow = $filter("YbDate")(item.purchaseDate, "yyyy-MM-dd HH:mm:ss");
              item.warrantyReleaseDateShow = $filter("YbDate")(item.warrantyReleaseDate, "yyyy-MM-dd HH:mm:ss");
              item.dispatchTimeShow = $filter("YbDate")(item.dispatchTime, "yyyy-MM-dd HH:mm:ss");
              item.repairWarrantyStatusShow = $filter("WarrantyStatus")(item.repairWarrantyStatus);
            });
          }
          return valT;
        });
      }

      $scope.detailTbConf = {
        scrollWidth: 1300,
        tableCol: [
          {
            name: "服务单号",
            dataField: "repairFormBillNo",
            width: 140,
            isShow: true,
          },
          {
            name: "是否核销",
            dataField: "hexiaoShow",
            width: 110,
            isShow: true,
            input: true,
            inputType: 'hexiao'
          },
          {
            name: "整车编码",
            dataField: "engineNo",
            width: 150,
            isShow: true,
          },
          {
            name: "服务人员",
            dataField: "technicianName",
            width: 100,
            isShow: true,
          },
          {
            name: "服务单位",
            dataField: "serviceOrgName",
            width: 150,
            isShow: true,
          },
          {
            name: "产品型号",
            dataField: "productModel",
            width: 100,
            isShow: true,
          },
          {
            name: "购机日期",
            dataField: "purchaseDateShow",
            width: 140,
            isShow: true,
          },
          {
            name: "出保日期",
            dataField: "warrantyReleaseDateShow",
            width: 140,
            isShow: true,
          },
          {
            name: "派工日期",
            dataField: "dispatchTimeShow",
            width: 145,
            isShow: true,
          },
          {
            name: "质保状态",
            dataField: "repairWarrantyStatusShow",
            width: 100,
            isShow: true,
          },
          {
            name: "计时表小时数",
            dataField: "workHours",
            width: 120,
            isShow: true,
          },
          {
            name: "旧件零件号",
            dataField: "returnMaterialsNo",
            width: 100,
            isShow: true,
          },
          {
            name: "旧件名称",
            dataField: "returnMaterialsName",
            width: 100,
            isShow: true,
          },
          {
            name: "备件来源",
            dataField: "returnPartsSource",
            width: 100,
            isShow: true,
          },
          {
            name: "数量",
            dataField: "returnAmount",
            width: 100,
            isShow: true,
          },
          {
            name: "批发价",
            dataField: "pifaPrice",
            width: 100,
            isShow: true,
          },
          {
            name: "费用合计",
            dataField: "totalFee",
            width: 100,
            isShow: true,
          },
        ]
      };

      var btnPermissionCode = {
        FANCHANGHEXIAO_AUDIT: window.ActionCode.FANCHANGHEXIAO_AUDIT,
      };

      $scope.btnPermission = {
        FANCHANGHEXIAO_AUDIT: true,
      };

      function setBtnPermission() {
        for (var key in btnPermissionCode) {
          $scope.btnPermission[key] = UserContextService.CheckPermission([
            btnPermissionCode[key],
          ]);
        }
      }

      // 审核单据
      $scope.auditData = function (val) {
        getDetail(val).then(function (value) {
          if (!value) {
            return;
          }

          $scope.orderObj = value;
          $scope.changeTab(2);
        });
      };

      $scope.handleAudit = function (auditStatus) {
        const message = $scope.orderObj.head.auditRemark;
        if (auditStatus === -1 && !message) {
            ybWidget.ShowMessage('请输入审核意见');
            $scope.submitted = true;
            return;
        }

        var param = {
          id: $scope.orderObj.head.id,
          auditStatus: auditStatus,
          auditRemark: message,
          auditDetails: $scope.orderObj.details.map(od => ({ id: od.id, hexiao: od.hexiao || false }))
        };
        ybHttp.Post("mt", "/hexiao/audit", param).then(function (resp) {
          if (resp.code !== 0) {
            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
            return;
          }
          ybWidget.ShowToaster('success', '操作成功');
          $scope.changeTab(0);
          getDataList();
        });
      };

      $scope.importData = function () {
        var param = {
            name: "发票",
            templateReqService: "mt",
            templateReqUrl: "/hexiao/fapiaoTmpDownload",
            importReqService: "mt",
            importReqUrl: "/hexiao/importFapiao",
            importErrorUrl: ""
        };
        ybWidget.ImportFile(param).then(function (data) {
            getDataList(1);
        });
      };

      $scope.selectHexiaoAll = function(val) {
        $scope.orderObj.details.forEach(od => {
          od.hexiao = val;
        })
      };

      $scope.checkDate = function (obj, startFiled, endFiled) {
        var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
        if (!!timeFormatObj.tStart) {
            obj[startFiled] = timeFormatObj.tStart;
        }
        if (!!timeFormatObj.tEnd) {
            obj[endFiled] = timeFormatObj.tEnd;
        }
      };

      (function () {
        UserContextService.SetBtnPermission(setBtnPermission);
        $scope.setFixedWidth();
        getDataList();
      })();
    },
  ]);
})(window, window.angular);
